import { BetaSchemaForm } from "@ant-design/pro-form";
import { PageContainer } from "@ant-design/pro-layout";
import { useAxiosPost, useLocation } from "@sker/sdk"
import { renderAdminPage, useWebSocket } from "@sker/ui"
import { useEffect, useState } from "react";
import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';

import { Button, Form } from "antd";

export const ScriptEditPage: React.FC<{}> = ({ }) => {
    const location = useLocation()
    const path = location.searchParams.get('path');
    const { fetch: downloadFromCode } = useAxiosPost(`autojs/core/web/file/downloadFromCode`)
    const { fetch: uploadFileFromLocal } = useAxiosPost(`autojs/core/web/file/uploadFileFromLocal`)
    const { latestMessage, connect } = useWebSocket('autojs/core/web/ws?uuid=RUN_DEBUG_SCRIPT_TASK_FILE', { manual: true })
    const [form] = Form.useForm()
    useEffect(() => {
        connect();
        setTimeout(() => {
            uploadFileFromLocal({ path });
        }, 1000)
    }, [])

    const [logData, setLogData] = useState<string>(``)
    const [code, setCode] = useState<string>(``)

    useEffect(() => {
        if (!latestMessage) return;
        const result = JSON.parse(latestMessage.data)
        const { type } = result;
        if (type === 'UPLOAD_FILE_FROM_LOCAL') {
            setCode(result.payload.data)
        }
    }, [latestMessage]);

    return <PageContainer>
        <div className="px-12px py-8px flex">
            <div className="px-12px py-8px">文件路径：<span className="text-16px font-bold">{path}</span></div>
            <div>
                <Button onClick={() => uploadFileFromLocal({ path })}>获取文件内容</Button>
            </div>
        </div>
        <BetaSchemaForm onFinish={async (e: any) => {
            downloadFromCode({
                path,
                code
            })
        }} form={form} layout={'vertical'} labelCol={{ span: 4 }} columns={[
            {
                title: '脚本内容', dataIndex: 'code', renderFormItem(schema, config, form, action) {
                    return <div className="flex">
                        <div className="w-1200px flex flex-col px-24px">
                            <div className="px-12px py-8px">
                                <CodeMirror height="150px" width="100%" onChange={e=>{
                                    setCode(e)
                                }} value={code} extensions={[
                                    javascript()
                                ]}></CodeMirror>
                            </div>
                            <code className="px-12px py-8px">
                                <div dangerouslySetInnerHTML={{ __html: logData }}></div>
                            </code>
                        </div>
                    </div>
                },
            }
        ]} />
    </PageContainer>
}

renderAdminPage(ScriptEditPage, 'autojs/core/web/taskFile')
